package com.xuxueli.commontdemo.util;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
/**
 * 操作虚拟机
 */
@Component
public class SSHLinux {
    private static final Logger log = LoggerFactory.getLogger(SSHLinux.class);
    private static String DEFAULTCHART = "UTF-8";
    Connection conn;

    /**
     * 登录主机
     *
     * @return 登录成功返回true，否则返回false
     */
    public void login(String ip, int port, String userName, String userPwd) {
        try {
            conn = new Connection(ip, port);
            conn.connect();//连接
            conn.authenticateWithPassword(userName, userPwd);//认证
            WebSocketServer.sendInfo("认证成功", "root");

        } catch (IOException e) {
            log.error("=========登录失败=========" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 远程执行shll脚本或者命令
     *
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    public void execute(String cmd, String userid) {
        String result = "";
        try {
            if (conn != null) {
                Session session = conn.openSession();
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART, userid);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    log.info("得到标准输出为空,链接conn:" + conn + ",执行的命令：" + cmd);
                } else {
                    log.info("执行命令成功,链接conn:" + conn + ",执行的命令：" + cmd);
                }
                session.close();
            }
        } catch (IOException e) {
            log.info("执行命令失败,链接conn:" + conn + ",执行的命令：" + cmd + "  " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void close() {
        conn.close();
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset, String userID) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                WebSocketServer.sendInfo(line, userID);
                log.info("为用户{}推送消息", userID);
            }
        } catch (UnsupportedEncodingException e) {
            log.error("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("解析脚本出错：" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }


    public static void main(String[] args) {
        SSHLinux sshLinux = new SSHLinux();
        sshLinux.login("10.7.128.112", 22, "root", "tzK2YTOy[i");

    }
}
